﻿using System;

using ManageSystemServer.Entity;
using ManageSystemServer.Service;

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace ManageSystemServer.Controllers
{
    [Route("user")]
    public class AdminController : Controller
    {
        public class Token
        {
            public string Bearer { get; set; }
        }
        //public class Tadmin
        //{
        //    public string AdminId { get; set; }
        //    public string Password { get; set; }
        //}
        //依赖注入
        private readonly IServiceProvider _services;

        private readonly AdminService _adminService;

        private readonly JwtTokenGenerator _jwtTokenGenerator;
        public AdminController(IServiceProvider services)
        {
            _services = services;
            _adminService = services.GetRequiredService<AdminService>();
            _jwtTokenGenerator = services.GetRequiredService<JwtTokenGenerator>();
        }
        // GET: api/<controller>
        [HttpGet("login")]
        [AllowAnonymous]
        public ActionResult<Token> Login_GetToken([FromBody] Admin? admin)
        {
            if (admin == null || admin.AdminId == null || admin.Password == null)
                return new BadRequestResult();
            if (_adminService.Authentize(admin.AdminId, admin.Password))
                //获取token
                return new Token { Bearer =  _jwtTokenGenerator.GetToken()};
            else
                return new BadRequestResult();

        }

        [HttpGet("admin")]
        [AllowAnonymous]
        public ActionResult<Admin> getAdmin()
        {
            return new Admin { AdminId = 1, Password = "2" };
        }
        // Put api/<controller>
        [HttpPut("register")]
        [AllowAnonymous]
        public ActionResult<bool> AddAdmin([FromBody] Admin? admin)
        {
            if (admin == null || admin.AdminId == null || admin.Password == null)
                return new BadRequestResult();
            return _adminService.AddAdmin(admin.AdminId, admin.Password);
        }

    }
}
